package taller2.controller.modes;

import java.awt.event.MouseEvent;

import javax.swing.JOptionPane;

import taller2.interfaces.Graph;
import taller2.interfaces.Node;
import taller2.utils.Point;
import taller2.utils.Utils;
import taller2.view.draws.DrawingArea;
import taller2.view.draws.GraphDrawer;

public class ConnectMode implements Mode {
	private Graph graph;
	
	// constructor
	public ConnectMode(Graph graph){
		this.graph = graph;
	}
	
	// when pressed selects a node, if a node is selected already, it connects both
	public void whenPressed(MouseEvent arg0, DrawingArea area) {
		GraphDrawer drawer = area.getDrawer();
		Point pos = new Point(arg0.getX(),arg0.getY());
		
		if(drawer.noNodesSelected()){
			drawer.selectCloseByNode(pos);
			area.repaint();
		}else{
			int index1 = drawer.getSelectedNodeIndex();
			if(drawer.selectCloseByNode(pos)){
				String weight = JOptionPane.showInputDialog ("Enter weight"); 
				if ((weight != null)&&(Utils.isANumber(weight))){
					int index2 = drawer.getSelectedNodeIndex();
					graph.ConnectNodes(index1, index2, Integer.parseInt(weight));
				}
				
				Node node1 = graph.getNodeByIndex(index1);
				node1.unselect();

				drawer.unselectNode();
				area.repaint();
			}
		}
	}

	public void whenReleased(MouseEvent arg0, DrawingArea area) {}

	public void whenDragged(MouseEvent arg0, DrawingArea area) {}

}
